import { Component } from 'react';

import {TabBar,ActionSheet,Datetime,Toast,Popup,CalendarField, Group, Boxs, Tab, SearchBar, Grid, Slide, Button, ScrollList, Avatar, Dialog, Badge} from 'saltui';
const { HBox, Box } = Boxs;
const {
  IconButton,
  ButtonGroup,
} = Button;
import BottomTab from '../../tab';
import './PageHome.less';



import {URLS,nodataIcon} from '../../../app/variables';

import DB from '../../../app/db';


let tabPage = '0';
let ActionSheetButton;

const Item  =  React.createClass({
  handleListClick: function(event) {
    
  },
  action:function(){
    let t = this;
    let tip = "";
    //动作面板选项
    let options = [];
    //动作面板选项标红下标
    let redIndex = -1;
    let publish = this.props.publish;
    if(publish == 0){
      options = ['发布','查看问卷','查看详情','编辑'];
      redIndex = 4;
      tip = "发布";
    }else if(publish == 1){
      options = ['停止','查看问卷','查看详情'];
      redIndex = 4;
      tip = "停止";
    }else{
      options = ['查看问卷','查看详情','编辑'];
      redIndex = 3;
    }
    //if((t.props.quesId == null || t.props.quesId == undefined || t.props.quesId == '') && publish == 0){
    if(publish == 0 || publish == 2){
      options.push('删除');
    }else{
      redIndex = -1;
    }
    if(this.props.addClickAble){
	    ActionSheetButton = ActionSheet.show({
	    options: options,
	    destructiveButtonIndex: redIndex,
	    maskClosable: true,
	  	}, (index) => {
        DB.QuesModuleAPI.entityIsExist({id:t.props.id}).then((content) => {
          if(content == 'exist'){
            if(index == 0){
              if(publish != 2){
                let msg = '确定要'+tip+'该问卷吗?';
                if(t.props.type == 'questionnaireExam' && publish == 1) msg = '考试正在进行中，确定要停止吗？';
                Dialog.confirm({
                title: '提示',
                locale: 'zh_CN',
                content: msg,
                onConfirm() {
                  DB.QuesModuleAPI.updateQuesPublish({
                    quesId:t.props.id,
                    publish:t.props.publish
                  }).then((result)=>{
                    if(result.type == 'success'){
                      Toast.show({
                        type: 'success',
                        content: result.message,
                      });
                    }else{
                      Toast.show({
                        type: 'error',
                        content: result.message,
                      });
                    }
                    t.props.refresh();
                  }).catch()
                },
                onCancel() {},
              });
              }else{
                t.jumpPage(t.props.id,"info");
              }
            }
            if(index == 1){
              if(publish != 2){
                t.jumpPage(t.props.id,"info");
              }else{
                t.jumpPage(t.props.id,"view");
              }   
            }
            if(index == 2){
              if(publish != 2){
                t.jumpPage(t.props.id,"view");
              }else{
                t.jumpPage(t.props.id,"edit");
              }
                
            }
            if(index == 3){
              if(publish != 2){
                t.jumpPage(t.props.id,"edit");
              }else{
                t.delet(this.props.id);
              }
            }
            if(index == 4){
                t.delet(this.props.id);
            }
          }else{
            Toast.show({
                type: 'error',
                content: '当前数据已删除',
            });
            t.props.refresh();
          }
        }).catch((error) => {
        });
	    
	    });
    }else{
    	this.props.changeClickAble();
    }
},
  //根据type页面跳转
  jumpPage:function(quesId,type){
      switch (type) {
        case "design" : this.checkDesgin(quesId);break;
        case "info": location.hash='questionnaire/ques_info/'+quesId+"/1/false/0";break;
        case "edit":location.hash='questionnaire/edit/'+quesId;break;
        case "view":location.hash='questionnaire/view/'+quesId;break;
      }
  },
  checkDesgin:function(quesId){
    let t = this;
    DB.QuesModuleAPI.getQuestTopic({
      quesId : quesId
    }).then((content)=>{
      if(content.type == 'success'){
        let data = content.data;
        if(data.isMobile == 0 ){
          Toast.show({
            type: 'error',
            content: '请前往电脑端修改该问卷！',
            onHide: function () {}
          });
        }else{
          if(data.publish == 1){
            Toast.show({
              type: 'error',
              content: '该问卷已经发布！',
              onHide: function () {}
            });
          }else{
            location.hash='questionnaire/design/'+quesId
          }
        }
        t.props.refresh();
      }
    }).catch();
  },

  delet:function(id){
    let t = this;
    Dialog.confirm({
      title: '提示',
      locale: 'zh_CN',
      content: '确定要删除该记录?',
      onConfirm() {
        DB.QuesModuleAPI.deletQuesById({quesId:id}).then((result)=>{
          if(result.type == 'success'){
            Toast.show({
              type: 'success',
              content: result.message,
            });
          }else{
            Toast.show({
              type: 'error',
              content: result.message,
            });
          }
          t.props.refresh();
        }).catch();
      },
      onCancel() {},
    });
  },
  render:function() {
    //type处理
    function formatType(type){
      switch (type){
        case '0':return '未发布';
        case '1':return '已发布';
        case '2':return '已到期';
        case 0:return '未发布';
        case 1:return '已发布';
        case 2:return '已到期';
      }
    }
    function typeName(type){
      switch (type){
        case 'questionnaireVote':return '投票';
        case 'questionnaireSurvey':return '调查';
        case 'questionnaireExam':return '考试';
      }
    }

    return <div onClick={this.action}>
      <Box className="t-BCf t-ML16 t-MR16 t-MT10 t-P12 t-R4">
        <HBox>
          <Box flex={1} className="t-LH1_4 t-PR10 t-FS16 t-omit2">{this.props.name}</Box>
          <Box className="t-FCddfontblue-40" ><i className="iconfont icon-more"></i></Box>
        </HBox>
        <Box className="t-FCddfontblue-40 t-LH1_4">{typeName(this.props.type)}</Box>
        <HBox className="t-MT6">
          <Box flex={1} className={this.props.publish==0?"t-FCorange":(this.props.publish==2?"t-FCred":"t-FCcyan")}><i className="iconfont icon-dotted t-FS14"></i>{formatType(this.props.publish)}</Box>
          <Box className="t-FCddfontblue-40">{this.props.createdDate.substring(0,10)}</Box>
        </HBox>
      </Box>
    </div>;
  }
});



export default class PageHome extends Component {

 constructor(props) {
    super(props);
    setTitle('问卷管理'); 
    let t = this;
    let userId = document.getElementById("userHiddenId").value;
    let winHeight ;
    winHeight = getScrollHigh(1,1,0);
    this.state = {
      userId:userId,
      ableClick:true,
      activeIndex: 0,
      activeTabIndex:tabPage,
      winHeight:winHeight,
      search1:'',
      //搜索
      visible1: false,

      //问卷类型
      typeArr:[{'value':'questionnaireVote','text':'投票'},{'value':'questionnaireSurvey','text':'调查'},{'value':'questionnaireExam','text':'考试'}],
      //问卷状态
      publishArr:[{'value':'1','text':'已发布'},{'value':'0','text':'未发布'},{'value':'2','text':'已到期'}],

      //选择的问卷类型
      type:"",
      //选择的问卷状态
      publish:"",
      //筛选条件展示位
      quesTypeArrow : false,
      quesPublishArrow : false,

      //筛选  问卷时间
      // time:null,
      startDate:null,
      endDate:null,
      addClickAble:true,
      noDataTip:'暂无数据'
    }; 
  }

  componentDidMount(){
    this.initButton();
    searchBarLimit(20);
  }

  //组件销毁执行
  componentWillUnmount(){
    setTitle('');
    Dialog.hide();
    if(ActionSheetButton){
      ActionSheetButton.close();
    }
    
  }

  //时间格式化   YYYY-MM-DD
  formatterDate(time){
    var date = new Date(time);
    var Y = date.getFullYear() + '-';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
    var D = date.getDate() < 10 ? "0" + (date.getDate()) : date.getDate();
    return Y+M+D;
  }

  changeClickAble(){
  	this.setState({
  		addClickAble:true
  	})
  }
  //分页列表请求前
  beforeFetch1(data,form){
  	this.setState({
  		addClickAble:false
  	});
    let search = form.value;
    if(search == undefined){
      data.search = this.state.search1;
    }else{
      data.search = form.value;
    }
    // let rows = data.pageSize;
    // data.rows = rows;

    if(this.state.startDate != null && this.state.startDate != ''){
      data.startDate = this.formatterDate(this.state.startDate);
    }
    if(this.state.endDate != null && this.state.endDate != ''){
      data.endDate = this.formatterDate(this.state.endDate);

    }
    if(this.state.type != ''){
      data.quesType = this.state.type;
    }
    if(this.state.publish != ''){
      data.quespublish = this.state.publish;
    }
    return data;
  }

  processData(data){
  	this.setState({
  		addClickAble:true
    });
  	return data;
  }
  //初始化按钮
  initButton(){
    //设置帮助
    //  dd.biz.navigation.setIcon({
    //     showIcon : true,//是否显示icon
    //     iconIndex : 2,//显示的iconIndex,如上图
    //     onSuccess : function(result) {
    //         /*结构
    //         {
    //         }*/
    //         //点击icon之后将会回调这个函数
    //         location.hash='document/help_index';
    //     },
    //     onFail : function(err) {
    //     //jsapi调用失败将会回调此函数
    //     }
    // });

    }

    /*跳到帮助*/
  skipHelp(path){
    let t = this;
    var userId = this.state.userId;
    dd.util.domainStorage.setItem({
     name:'document_'+userId , // 存储信息的key值
     value:'isLogin', // 存储信息的Value值
     onSuccess : function(info) {
          t.setState({
              isMask:false
             });
          location.hash=path;
     },
     onFail : function(err) {
     }
    });
    
  }
 //新增问卷
  addReport(){
    location.hash='questionnaire/add';
  }
//刷新列表
  refresh(){
    let value = this.state.search1;
    if(value == "") this.refs.reportComment_ref1.fetchData("bottom");
    else this.refs.reportComment_ref1.fetchData({value:value});
  }
  //改变筛选展示状态
  changeArrow(field){
    let t = this;
    let status = t.state[field];
    t.setState({
      [field]:!status
    })
  }


  //修改标题
  changeTitle(title){
    dd.biz.navigation.setTitle({
      title : title,//控制标题文本，空字符串表示显示默认文本
      onSuccess : function(result) {},
      onFail : function(err) {}
    });
  }

  //日期选择确认
  onOk(value,key){
    let t = this;
    if(key == "startDate" && t.state.endDate != null && t.state.endDate != ''){
      if(t.formatterDate(t.state.endDate) < t.formatterDate(value.value)){
        Toast.show({
          type: 'error',
          content: '开始日期不能大于结束日期'
        });
        return;
      }
    }
    if(key == "endDate" && t.state.startDate != null && t.state.startDate != ''){
      if(t.formatterDate(t.state.startDate) > t.formatterDate(value.value)){
        Toast.show({
          type: 'error',
          content: '结束日期不能小于开始日期'
        });
        return;
      }
    }
    t.setState({
      [key]:t.formatterDate(value.value)
    });
  }

  showSlot(id) {
    this[id].show();
  }

  render() {
    const t = this;
    let popHei=window.screen.height-60;
    const props = {
      locale: 'zh_CN',
      instantSearch: false,
      placeholder:'请输入问卷名称',
      hasHistory: true,
      searchDelay: 450,
      onEnter: (value) => { console.log(value);},
      onExit: () => { 
         t.setState({
          search1 :'',
          noDataTip:'暂无数据'
        },()=>{
           t.refs.reportComment_ref1.fetchData("top");
        });

       },
      onSearch: (value) =>{
        t.setState({
          search1 :value,
          noDataTip:'无搜索结果'
        },()=>{
          if(value != "") t.refs.reportComment_ref1.fetchData({value: value});
          else t.refs.reportComment_ref1.fetchData("top");
        });
      }
    };
    let winHeightStyle = {height: this.state.winHeight};
    const datetimeProps = {
      locale: 'zh-cn',
    };
    return (
      <div>  
          <div>
            <HBox className="t-BCf" vAlign="center">
              <Box flex={1}><SearchBar {...props} /></Box>
              <Box className="t-FCddblue" onClick={() => { t.setState({ visible1: true }); }}><i className="iconfont icon-filter t-FS18 t-FCblue t-LH44 t-PR10"/></Box>
            </HBox>
                <div style={winHeightStyle}>
                    <ScrollList
                      url={URLS.getAllQues}
                      dataType="json"
                      pageSize={10}
                      beforeFetch={this.beforeFetch1.bind(this)}
                      processData={this.processData.bind(this)}
                      noDataTip={this.state.noDataTip}
                      ref = 'reportComment_ref1'
                      noDataImage={nodataIcon}
                      currentPageKey="page"
                      >
                      <Item refresh={t.refresh.bind(t)} addClickAble={t.state.addClickAble} changeClickAble={t.changeClickAble.bind(this)}/>
                    </ScrollList>
                 </div>
          </div>
        <BottomTab activeIndex={0}/>
           {/*<IconButton className="add-new-page t-BCddblue" onClick={t.addReport.bind(this)}><i className="iconfont icon-plus t-FCf"></i></IconButton>*/}

        <Popup
          content={
            <div className="dd-popup-mail-right" style={{width:"280px",paddingTop:0,overflow:"auto",height:popHei}}>
              <HBox vAlign="center"
                    className="t-P16 t-PT14 t-PB0 t-FS16 t-MT4" onClick={t.changeArrow.bind(t,"quesTypeArrow")}>
                <Box flex={1} className="t-FC3">问卷类型</Box>
                <Box><i className={this.state.quesTypeArrow?"iconfont icon-arrow-down t-FCddblue":"iconfont icon-arrow-up t-FCddblue"} ></i></Box>
              </HBox>
              <HBox className={!this.state.quesTypeArrow?"t-FAC t-P12 t-PB6 t-PT6 t-fw":"t-DN"}>
                {
                  t.state.typeArr.map((item,key)=>(
                    <Box key={key} className={t.state.type == item.value?"t-BCddblue-20  t-FCddblue t-FS14 t-PL16 t-PR16 t-LH44 t-H44 t-M4 t-calc50-8 t-R4 t-omit":"t-BCf7 t-PL16 t-FS14 t-PR16 t-LH44 t-H44 t-M4 t-calc50-8 t-R4 t-omit"} onClick={()=>{
                      if(t.state.type == item.value){
                        t.setState({type:''})
                      }else{
                        t.setState({type:item.value})
                      }
                    }}>
                      {item.text}
                    </Box>
                  ))
                }
              </HBox>
              <HBox vAlign="center"
                    className="t-P16 t-PT16 t-PB0 t-FS16"
                    onClick={t.changeArrow.bind(t,"quesPublishArrow")}>
                <Box flex={1} className="t-FC3">问卷状态</Box>
                <Box><i className={this.state.quesPublishArrow?"iconfont icon-arrow-down t-FCddblue":"iconfont icon-arrow-up t-FCddblue"} ></i></Box>
              </HBox>
              <HBox className={!this.state.quesPublishArrow?"t-FAC t-P12 t-PB6 t-PT6 t-fw":"t-DN"}>
                {
                  t.state.publishArr.map((item,key)=>(
                    <Box key={key} className={t.state.publish == item.value?"t-BCddblue-20  t-FCddblue  t-PL16 t-PR16 t-LH44 t-H44 t-FS14 t-M4 t-calc50-8 t-R4 t-omit":"t-BCf7 t-FS14 t-PL16 t-PR16 t-LH44 t-H44 t-M4 t-calc50-8 t-R4 t-omit"} onClick={()=>{
                      if(t.state.publish == item.value){
                        t.setState({publish:''})
                      }else{
                        t.setState({publish:item.value})
                      }
                    }}>
                      {item.text}
                    </Box>
                  ))
                }
              </HBox>



              <p className="t-MT22 t-ML16 t-FS16 t-FS16 t-PB10">创建日期</p>
              <HBox vAlign="center" className="t-PL16 t-MT6">
                <Box className="t-FC9 t-FS14">开始</Box>
                <Box className="t-BCf7 t-LH32 t-R4 t-ML5" onClick={() => {t.showSlot('slot1');}} style={{width:'84%'}}>
                  <p className="t-FAC t-H26">{t.state.startDate} <i className="iconfont icon-calendar t-FS14 t-FCblue t-FR t-MR10"></i></p>
                  <Datetime
                    {...datetimeProps}
                    slotRef={s => this.slot1 = s}
                    title="日期选择"
                    placeholder="开始日期"
                    value={t.state.startDate}
                    columns={Datetime.YMD}
                    onConfirm={(value) => {t.onOk(value, 'startDate'); }}
                    onCancel={() => {  }}
                  />
                </Box>
              </HBox>
              <div className="t-H10"></div>
              <HBox vAlign="center" className="t-PL16">
                <Box className="t-FC9 t-FS14">结束</Box>
                <Box className="t-BCf7 t-LH32 t-R4 t-col-6 t-ML5" onClick={() => {t.showSlot('slot2');}} style={{width:'84%'}}>
                  <p className="t-FAC t-H26">{t.state.endDate}<i className="iconfont icon-calendar t-FS14  t-FCblue t-FR t-MR10"></i></p>
                  <Datetime
                    {...datetimeProps}
                    slotRef={s => this.slot2 = s}
                    title="日期选择"
                    placeholder="结束日期"
                    value={t.state.endDate}
                    columns={Datetime.YMD}
                    onConfirm={(value) => { t.onOk(value, 'endDate'); }}
                    onCancel={() => {  }}
                  />
                </Box>
              </HBox>


              <div className="t-bottom-fixed t-BT0" style={{    borderTop:0,bottom:'0',width:'100%'}}>
                <ButtonGroup onClick={() => { Popup.hide(); }}>
                  <Button type="secondary" display="inline" onClick={() => { t.setState({type:"",publish:"",startDate:'',endDate:'',noDataTip:'暂无数据'},()=>{t.refresh()}) }}>重置</Button>
                  <Button type="primary" display="inline" onClick={() => {this.setState({ visible1: false,noDataTip:'无搜索结果' });t.refresh()}}>确定</Button>
                </ButtonGroup>
              </div>
            </div>
          }
          animationType="slide-left"
          onMaskClick={() => { this.setState({ visible1: false }); }}
          visible={this.state.visible1}
        >
          {null}
        </Popup>
      </div>
      );
    }
}


